package com.boby.homecamera.util

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import java.io.File

object FileUtils {

    /**
     * 获取本地视频的第一帧
     * @param localPath
     * @return
     */
    fun getLocalVideoBitmap(localPath: String?): Pair<Bitmap?,Int?>? {
        var bitmap: Bitmap? = null
        val retriever = MediaMetadataRetriever()
//            val retriever = FFmpegMediaMetadataRetriever()
        var videoRotation = 0
        try {
            //根据文件路径获取缩略图
            retriever.setDataSource(File(localPath).absolutePath)
//            retriever.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM)
//                val rotation = retriever.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)
//                if(rotation != null){
//                    try {
//                        videoRotation =  rotation.toFloat()
//                    }catch (e:Exception){
//                        e.printStackTrace()
//                    }
//                }
            //获得第一帧图片
            bitmap = retriever.frameAtTime

            val orientation = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)
//                BLog.d(TAG," orientation :$orientation" )
            try {
                videoRotation = Integer.parseInt(orientation)
            }catch (e:Exception){
                e.printStackTrace()
            }

        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } finally {
            retriever.release()
        }
        if(bitmap != null && videoRotation != 0){
//            BLog.d(TAG,"getLocalVideoBitmap rotation:${videoRotation} ")
//                return Pair(BitmapUtil.getRotateBitmap(bitmap,videoRotation.toFloat()),videoRotation)
            return Pair(bitmap,videoRotation)
        }


        return Pair(bitmap,videoRotation.toInt())
    }
}